package com.jiazhong.mingxing.project.bookstore.front.service.impl;

import com.jiazhong.mingxing.project.bookstore.commons.bean.Book;
import com.jiazhong.mingxing.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.mingxing.project.bookstore.commons.util.JsonResult;
import com.jiazhong.mingxing.project.bookstore.commons.util.ResultTool;
import com.jiazhong.mingxing.project.bookstore.front.service.BookService;
import com.jiazhong.mingxing.project.bookstore.front.service.ShoppingCartService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private BookService bookService;

    public static final String SHOPPING_CART = "shopping_cart:";

    @Override
    public JsonResult addCart(String bookId, HttpServletRequest request) {
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        // 1. 获取到userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 判断这本图书是否在该用户的购物车中
        Boolean hasKey = forHash.hasKey(SHOPPING_CART + userId.toString(), bookId);
        if (hasKey) {
            // 3. 已存在，数量+1
            forHash.increment(SHOPPING_CART + userId.toString(), bookId, 1);
            return ResultTool.success("success");
        }
        // 4. 不存在，将该本图书加入这个用户的购物车
        forHash.put(SHOPPING_CART + userId.toString(), bookId, "1");
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findCartByUserId(HttpServletRequest request) {
        // 1. 获取到userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 获取到该用户在redis中的购物车
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        Map<Object, Object> myCart = forHash.entries(SHOPPING_CART + userId.toString());
        // 3. 将map集合的内容存放到list集合（数据转换）
        List<Book> list = new ArrayList();

        myCart.forEach((k, v) -> {
            String bookId = k.toString();
            int number = Integer.parseInt(v.toString());
            Book book = bookService.getById(bookId);
            book.setNumber(number);
            list.add(book);
        });
        // 4. 返回该购物车
        return ResultTool.success(list);
    }

    @Override
    public JsonResult findCartByUserId(String token) {
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 获取到该用户在redis中的购物车
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        Map<Object, Object> myCart = forHash.entries(SHOPPING_CART + userId.toString());
        // 3. 将map集合的内容存放到list集合（数据转换）
        List<Book> list = new ArrayList();

        myCart.forEach((k, v) -> {
            String bookId = k.toString();
            int number = Integer.parseInt(v.toString());
            Book book = bookService.getById(bookId);
            book.setNumber(number);
            list.add(book);
        });
        // 4. 返回该购物车
        return ResultTool.success(list);
    }

    @Override
    public JsonResult updateCartNumber1(String bookId, HttpServletRequest request) {
        // 1. 获取到userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 判断指定图书的数量是否能够进行减的运算
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        int number = Integer.parseInt(forHash.get(SHOPPING_CART + userId.toString(), bookId).toString());
        if (number <= 0) {
            return ResultTool.fail("该商品不存在", 500);
        } else if (number == 1) {
            // 3. 当数量为0时，应该执行删除操作
            forHash.delete(SHOPPING_CART + userId.toString(), bookId);
            return ResultTool.success("删除成功");
        } else {
            // 3. 更新购物车中指定图书的数量
            forHash.increment(SHOPPING_CART + userId.toString(), bookId, -1);
            return ResultTool.success("success");
        }
    }

    @Override
    public JsonResult updateCartNumber2(String bookId, HttpServletRequest request) {
        // 1. 获取到userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 将购物车中的图书数量+1
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        // 3. 附加内容：判断库存是否充足
        // 这里的代码：库存数量大于当前购物车中钙商品的数量

        forHash.increment(SHOPPING_CART + userId.toString(), bookId, 1);
        return ResultTool.success("success");
    }

    @Override
    public JsonResult updateCartNumber3(String bookId, HttpServletRequest request, int number) {
        // 1.判断数量是否符合要求：大于0，小于库存数量（你们完成）
        if (number <= 0) {
            return ResultTool.fail("数量必须大于0", 500);
        }
        // 2.获取到userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 3.更新购物车中的数量
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        forHash.put(SHOPPING_CART + userId.toString(), bookId, number + "");
        return ResultTool.success("success");
    }

    @Override
    public JsonResult removeCartByBookId(String bookId, HttpServletRequest request) {
        // 1. 获取userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 删除redis中指定图书的数据
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        Long delete = forHash.delete(SHOPPING_CART + userId.toString(), bookId);
        if (delete == 0) {
            return ResultTool.fail("删除购物车失败", 500);
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult removeCartByBatch(String bookIds, HttpServletRequest request) {
        // 1. 获取userId
        String token = request.getHeader("token");
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 将bookIds转换成数组
        String[] strings = bookIds.split(",");
        // 2. 删除redis中指定那些图书的数据
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        for (int i = 0; i < strings.length; i++) {
            forHash.delete(SHOPPING_CART + userId.toString(), strings[i]);
        }

        return ResultTool.success("success");
    }
}
